package com.blue.Impl.ai;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blue.common.constant.CommonConstant;
import com.blue.common.utils.ConvertUtils;
import com.blue.mapper.ai.ChatRecordMapper;
import com.blue.po.ai.ChatRecordPO;
import com.blue.po.ai.UserSubscribePO;
import com.blue.service.ai.IChatRecordService;
import com.blue.service.ai.IUserSubscribeService;
import com.blue.vo.ai.ChatRecordVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class ChatRecordServiceImpl extends ServiceImpl<ChatRecordMapper, ChatRecordPO> implements IChatRecordService {

    @Autowired
    private IUserSubscribeService userSubscribeService;

    @RabbitListener(queues = "chatQueue")
    public void record(String content) {
        ChatRecordVO chatRecordVO = JSON.parseObject(content, ChatRecordVO.class);
        String msg = chatRecordVO.getContent();
        //判断类型
        if ((msg.contains("生成") && msg.contains("图片")) || StringUtils.isNotBlank(chatRecordVO.getImgCode())) {
            chatRecordVO.setContentType(CommonConstant.IMG);
        } else {
            chatRecordVO.setContentType(CommonConstant.TEXT);
        }
        //更新Token
        LambdaUpdateWrapper<UserSubscribePO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(UserSubscribePO::getUserId, chatRecordVO.getUserId())
                .eq(UserSubscribePO::getIsFlag, CommonConstant.YES);
        if (CommonConstant.TEXT.equals(chatRecordVO.getContentType())) {
            int length = msg.length();
            //开启了上下文Token数量翻倍
            if (StringUtils.isNotBlank(chatRecordVO.getContextId())) {
                length = length * 3;
            }
            updateWrapper.setSql("token_num = token_num + " + (length * 2));
        } else if (CommonConstant.IMG.equals(chatRecordVO.getContentType())) {
            updateWrapper.setSql("token_num = token_num + 100");
        }
        userSubscribeService.update(updateWrapper);
        ChatRecordPO chatRecordPO = ConvertUtils.convert(ChatRecordPO.class, chatRecordVO);
        this.save(chatRecordPO);
    }
}
